const connection = require('../app/database');

class CommentService {
  async createComment(momentId, content, userId) {
    try {
      const sql = `INSERT INTO comment (moment_id, content, user_id) VALUES (?, ?, ?)`;
      const [result] = await connection.execute(sql, [momentId, content, userId]);
      console.log(result);
      return result;
    } catch (e) {
      console.log(e);
    }
  }

  async reply(commentId, content, momentId, id) {
    try {
      const sql = `INSERT INTO comment (moment_id, content, user_id ,comment_id) VALUES (?, ?, ?,?)`;
      const [result] = await connection.execute(sql, [momentId, content, id, commentId]);
      console.log(result);
      return result;
    } catch (e) {
      console.log(e);
    }
  }

  async updateComment(commentId, content) {
    try {
      const sql = `UPDATE comment SET content = ? WHERE id = ?`;
      const [result] = await connection.execute(sql, [content, commentId]);
      console.log(result);
      return result;
    } catch (e) {
      console.log(e);
    }
  }

  async deleteComment(commentId) {
    try {
      const sql = `DELETE FROM comment WHERE id = ?`;
      const [result] = await connection.execute(sql, [commentId]);
      console.log(result);
      return result;
    } catch (e) {
      console.log(e);
    }
  }

  async getComments(momentId) {
    console.log(momentId, 'momentId');
    try {
      const sql = `
            SELECT
             m.id , m.content,m.comment_id commentId ,m.createAt creatTime,
             JSON_OBJECT('id',u.id,'name',u.name,'avatar',u.avatar_url) user
             FROM comment m
             LEFT JOIN users u ON u.id = m.user_id
             WHERE moment_id = ?;`;
      const [result] = await connection.execute(sql, [momentId]);
      console.log(result);
      return result;
    } catch (e) {
      console.log(e);
    }
  }
}

module.exports = new CommentService();
